import { lazyBatchReport } from '../report/index'

export default function error() {
  // 捕获资源加载失败的错误：js css img等
  window.addEventListener(
    'error',
    (e) => {
      const { target } = e
      if (!target) {
        return
      }

      if (target.src || target.href) {
        const url = target.src || target.href
        const reportData = {
          type: 'error',
          subType: 'resource',
          url,
          target,
          html: target.outerHTML,
          pageUrl: window.location.href,
          path: e.path,
        }

        // 数据上报
        lazyBatchReport(reportData)
      }
    },
    true,
  )

  // 捕获js错误
  window.onerror = function (message, url, lineNo, columnNo, error) {
    const reportData = {
      type: 'error',
      subType: 'js',
      message,
      url,
      lineNo,
      columnNo,
      error,
      pageUrl: window.location.href,
      startTime: performance.now(),
    }

    // 数据上报
    lazyBatchReport(reportData)
  }

  // 捕获promise错误 async await
  window.addEventListener(
    'unhandledrejection',
    (e) => {
      const { reason } = e
      const reportData = {
        type: 'error',
        subType: 'promise',
        reason: e.reason?.stack,
        pageUrl: window.location.href,
        startTime: performance.now(),
      }
      // 数据上报
      lazyBatchReport(reportData)
    },
    true,
  )
}
